﻿namespace Access.Duoc
{
    using ConfigDatabase.Class;
    using Npgsql;
    using Access;
    using BaseClass.Chung;
    using BaseClass.Duoc;
    using System;
    using System.Data;

    public class DXuatBanLe
    {
        private ConnectDatabase _condata;
        private NpgsqlConnection _conn;
        private General _xuli;
        public int pLoaiXuat;

        public DXuatBanLe()
        {
            this.pLoaiXuat = 0;
            this._condata = new ConnectDatabase();
            this._xuli = new General(this._condata);
        }

        public DXuatBanLe(ConnectDatabase condata)
        {
            this.pLoaiXuat = 0;
            this._condata = condata;
            this._xuli = new General(this._condata);
        }

        public string f_get_capmaphieu(string kihieu)
        {
            return (kihieu + DateTime.Now.ToString("yy") + this.f_get_capsophieu().ToString());
        }

        public long f_get_capsophieu()
        {
            long num = 0L;
            try
            {
                num = long.Parse(this._xuli.f_Get_dulieu("select max(" + dtoDXuatBanLe.columnSOPHIEU + ") as sophieu  from " + this._xuli.pSchema + "." + dtoDXuatBanLe.tableName + " where to_char(" + dtoDXuatBanLe.columnNGAY + ",'yyyy')='" + DateTime.Now.ToString("yyyy") + "'").Tables[0].Rows[0][0].ToString());
            }
            catch
            {
            }
            return (num + 1L);
        }

        public bool f_huy_xuatbanle(dtoDXuatBanLe xuatban)
        {
            bool flag;
            this._conn = new NpgsqlConnection(this._condata.StringConnect);
            this._conn.Open();
            try
            {
                string str = this._xuli.pSchema + ".";
                string sql = string.Concat(new object[] { "select ", dtoDXuatBanLeCT.columnID, " as idct from ", str, dtoDXuatBanLeCT.tableName, " where ", dtoDXuatBanLeCT.columnIDXUATKHOBANLE, "=", xuatban.pID });
                DataTable table = this._xuli.f_Get_dulieu(sql).Tables[0];
                NpgsqlTransaction transaction = this._conn.BeginTransaction();
                int num = 0;
                num = 0;
                while (num < table.Rows.Count)
                {
                    dtoDXuatBanLeCT chitiet = new dtoDXuatBanLeCT(this._condata) {
                        pID = long.Parse(table.Rows[num]["idct"].ToString())
                    };
                    chitiet.Load();
                    if (!this.f_huy_xuatbanlechitiet(chitiet, this._conn))
                    {
                        break;
                    }
                    num++;
                }
                if (num < table.Rows.Count)
                {
                    transaction.Rollback();
                    return false;
                }
                transaction.Commit();
                xuatban.Delete();
                flag = true;
            }
            catch
            {
                flag = false;
            }
            finally
            {
                this._conn.Close();
                this._conn.Dispose();
            }
            return flag;
        }

        public bool f_huy_xuatbanlechitiet(dtoDXuatBanLeCT chitiet)
        {
            bool flag;
            this._conn = new NpgsqlConnection(this._condata.StringConnect);
            this._conn.Open();
            try
            {
                string str = this._xuli.pSchema + ".";
                NpgsqlTransaction transaction = this._conn.BeginTransaction();
                if (!this.f_huy_xuatbanlechitiet(chitiet, this._conn))
                {
                    transaction.Rollback();
                    return false;
                }
                transaction.Commit();
                flag = true;
            }
            catch
            {
                flag = false;
            }
            finally
            {
                this._conn.Close();
                this._conn.Dispose();
            }
            return flag;
        }

        private bool f_huy_xuatbanlechitiet(dtoDXuatBanLeCT chitiet, NpgsqlConnection connect)
        {
            try
            {
                string str = this._xuli.pSchema + ".";
                string sql = string.Concat(new object[] { "select ", dtoDTheoDoiXuatKho.columnIDNHAPKHOCT, " as idnhapct,", dtoDTheoDoiXuatKho.columnSOLUONG, " as soluong,", dtoDTheoDoiXuatKho.columnID, " as id from ", str, dtoDTheoDoiXuatKho.tableName, " where ", dtoDTheoDoiXuatKho.columnIDXUATKHOCT, "=", chitiet.pID });
                DataTable table = this._xuli.f_Get_dulieu(sql).Tables[0];
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    string str3 = "update " + str + dtoDNhapKhoCT.tableName + "  set " + dtoDNhapKhoCT.columnSOLUONGXUAT + "=" + dtoDNhapKhoCT.columnSOLUONGXUAT + "-" + table.Rows[i]["soluong"].ToString() + " where " + dtoDNhapKhoCT.columnID + "=" + table.Rows[i]["idnhapct"].ToString();
                    string str4 = "delete from " + str + dtoDTheoDoiXuatKho.tableName + " where " + dtoDTheoDoiXuatKho.columnID + "=" + table.Rows[i]["id"].ToString();
                    if ((this._xuli.f_Update_dulieu(str3, connect) == -1) || (this._xuli.f_Update_dulieu(str4, connect) == -1))
                    {
                        return false;
                    }
                }
                if (!chitiet.Delete(connect))
                {
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public long f_insert_xuatbanle(dtoDXuatBanLe xuatban, dtoDXuatBanLeCT[] chitiet, HangSo.NhomKhachHang.enNhomKhachHang nhomkh)
        {
            long num2;
            this._conn = new NpgsqlConnection(this._condata.StringConnect);
            this._conn.Open();
            try
            {
                xuatban.pKIHIEU = this.f_get_capmaphieu("PX");
                xuatban.pSOPHIEU = this.f_get_capsophieu();
                xuatban.pID = long.Parse(this._xuli.f_Get_CapID());
                if (!xuatban.Insert(this._conn))
                {
                    return 0L;
                }
                NpgsqlTransaction transaction = this._conn.BeginTransaction();
                int index = 0;
                index = 0;
                while (index < chitiet.Length)
                {
                    chitiet[index].pIDXUATKHOBANLE = xuatban.pID;
                    if (chitiet[index].pID == 0L)
                    {
                        chitiet[index].pID = long.Parse(this._xuli.f_Get_CapID());
                    }
                    if (!this.f_insert_xuatbanlect(chitiet[index], this._conn, nhomkh, xuatban.pIDDANGNHAP))
                    {
                        break;
                    }
                    index++;
                }
                if (index == chitiet.Length)
                {
                    transaction.Commit();
                    return xuatban.pID;
                }
                xuatban.Delete();
                num2 = 0L;
            }
            catch
            {
                num2 = 0L;
            }
            finally
            {
                this._conn.Close();
                this._conn = null;
            }
            return num2;
        }

        public bool f_insert_xuatbanlect(dtoDXuatBanLeCT chitiet, NpgsqlConnection conn, HangSo.NhomKhachHang.enNhomKhachHang nhomkh, int iddangnhap)
        {
            decimal num = 0M;
            DataTable table = new DTonKho(this._condata).f_load_tonkhochitiet(nhomkh, chitiet.pIDDUOCPHAM).Tables[0];
            string str = "";
            DataRow[] rowArray = table.Select("iddp=" + chitiet.pIDDUOCPHAM);
            num = 0M;
            int index = 0;
            bool flag = false;
            for (index = 0; index < rowArray.Length; index++)
            {
                string str2;
                flag = true;
                dtoDTheoDoiXuatKho kho = new dtoDTheoDoiXuatKho(this._condata);
                chitiet.pDONGIA = decimal.Parse(rowArray[index]["giaban"].ToString());
                kho.pDONGIA = chitiet.pDONGIA;
                kho.pIDDANGNHAP = iddangnhap;
                kho.pIDDUOCPHAM = chitiet.pIDDUOCPHAM;
                kho.pIDNHAPKHOCT = long.Parse(rowArray[index]["idnhapct"].ToString());
                kho.pTENMAYTINH = Environment.MachineName;
                kho.pIDLOAIXUAT = HangSo.LoaiXuatKho.enLoaiXuatKho.XuatBanLe.GetHashCode();
                kho.pIDXUATKHOCT = chitiet.pID;
                kho.pID = long.Parse(this._xuli.f_Get_CapID());
                if (chitiet.pSOLUONG <= (decimal.Parse(rowArray[index]["soluongton"].ToString()) + num))
                {
                    kho.pSOLUONG = chitiet.pSOLUONG - num;
                    num += kho.pSOLUONG;
                    if (kho.Insert(this._conn))
                    {
                        str2 = str;
                        str = str2 + rowArray[index]["idnhapct"].ToString() + "#" + kho.pSOLUONG.ToString() + ";";
                        this._xuli.f_Update_dulieu(string.Concat(new object[] { "update ", this._xuli.pSchema, ".", dtoDNhapKhoCT.tableName, " set ", dtoDNhapKhoCT.columnSOLUONGXUAT, "=", dtoDNhapKhoCT.columnSOLUONGXUAT, "+", kho.pSOLUONG, " where ", dtoDNhapKhoCT.columnID, "=", rowArray[index]["idnhapct"].ToString() }));
                    }
                    break;
                }
                num += decimal.Parse(rowArray[index]["soluongton"].ToString());
                kho.pSOLUONG = decimal.Parse(rowArray[index]["soluongton"].ToString());
                if (kho.Insert(this._conn))
                {
                    str2 = str;
                    str = str2 + rowArray[index]["idnhapct"].ToString() + "#" + kho.pSOLUONG.ToString() + ";";
                    this._xuli.f_Update_dulieu(string.Concat(new object[] { "update ", this._xuli.pSchema, ".", dtoDNhapKhoCT.tableName, " set ", dtoDNhapKhoCT.columnSOLUONGXUAT, "=", dtoDNhapKhoCT.columnSOLUONGXUAT, "+", kho.pSOLUONG, " where ", dtoDNhapKhoCT.columnID, "=", rowArray[index]["idnhapct"].ToString() }));
                }
                else
                {
                    break;
                }
            }
            if (!flag)
            {
                return false;
            }
            chitiet.pSOLUONG = num;
            if (!chitiet.Insert(this._conn))
            {
                this._xuli.f_Update_dulieu("update " + this._xuli.pSchema + "." + dtoDNhapKhoCT.tableName + " set " + dtoDNhapKhoCT.columnSOLUONGXUAT + "=" + dtoDNhapKhoCT.columnSOLUONGXUAT + "-" + str.Trim(new char[] { ';' }).Split(new char[] { '#' })[1] + " where " + dtoDNhapKhoCT.columnID + "=" + str.Trim(new char[] { ';' }).Split(new char[] { '#' })[0]);
                return false;
            }
            return true;
        }

        public DataTable f_loaddata_xuatban(long id, string tungay, string denngay)
        {
            DataTable table = new DataTable();
            string str = "";
            if (this.pLoaiXuat != 0)
            {
                str = string.Concat(new object[] { " and a.", dtoDXuatBanLe.columnIDLOAIXUAT, "=", this.pLoaiXuat });
            }
            string str2 = this._condata.Schema + ".";
            string sql = string.Concat(new object[] { 
                "select a.", dtoDXuatBanLe.columnID, " as id,a.", dtoDXuatBanLe.columnKIHIEU, " as sophieu,to_char(", dtoDXuatBanLe.columnNGAY, ",'dd/mm/yyyy hh24:mi') as ngay,a.", dtoDXuatBanLe.columnIDDANGNHAP, " as iddangnhap,a.", dtoDXuatBanLe.columnHOTEN, " as hoten,a.", dtoDXuatBanLe.columnDIACHI, " as diachi,a.", dtoDXuatBanLe.columnNAMSINH, " as namsinh,case when a.", dtoDXuatBanLe.columnIDGIOITINH, 
                "=", HangSo.enGioiTinh.Nam.GetHashCode(), " then 'Nam' else 'Nữ' end as phai,a.", dtoDXuatBanLe.columnTONGTIEN, " as tongtien,a.", dtoDXuatBanLe.columnCHIETKHAU, " as chietkhau,b.", dtoDMDangNhap.columnTENNGUOIDUNG, " as tennguoidangnhap,a.", dtoDXuatBanLe.columnSOLANIN, " as solanin from ", str2, dtoDXuatBanLe.tableName, " a left join ", str2, dtoDMDangNhap.tableName, 
                " b on a.", dtoDXuatBanLe.columnIDDANGNHAP, "=b.", dtoDMDangNhap.columnID, " where 1=1 ", (id == 0L) ? "" : string.Concat(new object[] { " and a.", dtoDXuatBanLe.columnID, "=", id }), (tungay == "") ? "" : (" and to_timestamp(to_char(a." + dtoDXuatBanLe.columnNGAY + ",'dd/mm/yyyy'),'dd/mm/yyyy')>=to_timestamp('" + tungay + "','dd/mm/yyyy')"), (denngay == "") ? "" : (" and to_timestamp(to_char(a." + dtoDXuatBanLe.columnNGAY + ",'dd/mm/yyyy'),'dd/mm/yyyy')<=to_timestamp('" + denngay + "','dd/mm/yyyy')"), str, " order by a.", dtoDXuatBanLe.columnNGAY, " desc,a.", dtoDXuatBanLe.columnID, " desc"
             });
            return this._xuli.f_Get_dulieu(sql).Tables[0];
        }

        public DataTable f_loaddata_xuatbanct(long idxuat)
        {
            DataTable table = new DataTable();
            string str = this._condata.Schema + ".";
            string sql = string.Concat(new object[] { 
                "select b.", dtoDXuatBanLeCT.columnIDXUATKHOBANLE, " as idxuatbanle,b.", dtoDXuatBanLeCT.columnID, " as id,b2.", dtoDDMDuocPham.columnID, " as iddp,b2.", dtoDDMDuocPham.columnTEN, " as tendp,b2.", dtoDDMDuocPham.columnMA, " as madp,b2.", dtoDDMDuocPham.columnDVT, " as dvt,b2.", dtoDDMDuocPham.columnMAVACH, " as tenhoatchat,b3.", dtoDTheoDoiXuatKho.columnSOLUONG, 
                " as soluong,b3.", dtoDTheoDoiXuatKho.columnSOLUONG, "*b3.", dtoDTheoDoiXuatKho.columnDONGIA, " as thanhtien,b3.", dtoDTheoDoiXuatKho.columnSOLUONG, "*b3.", dtoDTheoDoiXuatKho.columnDONGIA, "*(1+(b.", dtoDXuatBanLeCT.columnTHUE, "+0.0)/100) as tiensauthue,b.", dtoDXuatBanLeCT.columnIDDANGNHAP, " as iddangnhap,b4.", dtoDNhapKhoCT.columnLO, " as losx,b4.", dtoDNhapKhoCT.columnHANGSX, 
                ",to_char(b4.", dtoDNhapKhoCT.columnHANDUNG, ",'dd/mm/yyyy') as handung,b4.", dtoDNhapKhoCT.columnGIAMUA, " as giamua,b3.", dtoDTheoDoiXuatKho.columnDONGIA, " as giaban,b41.", dtoDDMViTriTrongKho.columnTEN, " as tenvitrikho,b.", dtoDXuatBanLeCT.columnTHUE, " as thue from ", str, dtoDXuatBanLe.tableName, " a inner join ", str, dtoDXuatBanLeCT.tableName, 
                " b on a.", dtoDXuatBanLe.columnID, "=b.", dtoDXuatBanLeCT.columnIDXUATKHOBANLE, " inner join ", str, dtoDDMDuocPham.tableName, " b2 on b.", dtoDXuatBanLeCT.columnIDDUOCPHAM, "=b2.", dtoDDMDuocPham.columnID, " inner join ", str, dtoDTheoDoiXuatKho.tableName, " b3 on b.", dtoDXuatBanLeCT.columnID, 
                "=b3.", dtoDTheoDoiXuatKho.columnIDXUATKHOCT, " inner join ", str, dtoDNhapKhoCT.tableName, " b4 on b3.", dtoDTheoDoiXuatKho.columnIDNHAPKHOCT, "=b4.", dtoDNhapKhoCT.columnID, " left join ", str, dtoDDMViTriTrongKho.tableName, " b41 on b4.", dtoDNhapKhoCT.columnIDVITRIKHO, "=b41.", dtoDDMViTriTrongKho.columnID, 
                " where a.", dtoDXuatBanLe.columnID, "=", idxuat, " and b3.", dtoDTheoDoiXuatKho.columnIDLOAIXUAT, "=", HangSo.LoaiXuatKho.enLoaiXuatKho.XuatBanLe.GetHashCode(), " order by a.", dtoDXuatBanLe.columnNGAY, " desc"
             });
            return this._xuli.f_Get_dulieu(sql).Tables[0];
        }

        public long f_update_xuatbanle(dtoDXuatBanLe xuatban, dtoDXuatBanLeCT[] chitiet, HangSo.NhomKhachHang.enNhomKhachHang nhomkh)
        {
            try
            {
                dtoDXuatBanLe le = new dtoDXuatBanLe(this._condata) {
                    pID = xuatban.pID
                };
                le.Load();
                if (!this.f_huy_xuatbanle(le))
                {
                    return 0L;
                }
                return this.f_insert_xuatbanle(xuatban, chitiet, nhomkh);
            }
            catch
            {
                return 0L;
            }
        }
    }
}

